package com.mega.ttexp.mixin;

import net.minecraft.entity.CreatureAttribute;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.LivingEntity;
import net.minecraft.particles.ParticleTypes;
import net.minecraft.tags.EntityTypeTags;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;

/**
 * @author MegaDarkness
 */
@Mixin(LivingEntity.class)
public abstract class LivingEntityMixin extends Entity {
    public LivingEntityMixin(EntityType<?> p_i48580_1_, World p_i48580_2_) {
        super(p_i48580_1_, p_i48580_2_);
    }

    @Shadow
    public abstract CreatureAttribute getMobType();

    private boolean isTitan() {
        return  (EntityTypeTags.getAllTags().getTag(new ResourceLocation("forge:shly")).contains(getType()) || EntityTypeTags.getAllTags().getTag(new ResourceLocation("forge:t")).contains(getType()));
    }

    @Shadow public int deathTime;

    /**
     * @reason 让kill对泰坦生物无效
     */
    @Inject(method = "kill", at = @At("HEAD"), cancellable = true)
    public void onKill(CallbackInfo ci) {
        try {
            if (isTitan()) {
                ci.cancel();
            }
        } catch (NullPointerException n){
            n.printStackTrace();
        }
    }

    @Override
    public void remove() {
            try {
                if (isTitan() && deathTime <5) {
                    return;
                }
            } catch (NullPointerException n){
                n.printStackTrace();
            }
        super.remove();
    }

    /**
     * @author mega
     */
    @SuppressWarnings("ConstantConditions")
    @Overwrite
    protected void tickDeath() {
        ++this.deathTime;
        if (!isTitan() && this.deathTime == 20) {
            this.remove((Object)this instanceof net.minecraft.entity.player.ServerPlayerEntity); //Forge keep data until we revive player

            for(int i = 0; i < 20; ++i) {
                double d0 = this.random.nextGaussian() * 0.02D;
                double d1 = this.random.nextGaussian() * 0.02D;
                double d2 = this.random.nextGaussian() * 0.02D;
                this.level.addParticle(ParticleTypes.POOF, this.getRandomX(1.0D), this.getRandomY(), this.getRandomZ(1.0D), d0, d1, d2);
            }
        }
        if (isTitan() && this.deathTime >= Math.max(getPersistentData().getInt("titan_death"), 440)) {
            this.remove((Object)this instanceof net.minecraft.entity.player.ServerPlayerEntity); //Forge keep data until we revive player
        }

    }
}
